<template>
  <view class="history-container">
    <!-- 列表 -->
    <z-paging ref="pagingRef" v-model="dataList" @query="queryList">
      <template #top>
        <!-- 筛选栏 -->
        <view class="filter-bar">
          <view class="filter-item" @click="showFeedTypeSelector = true">
            <text class="filter-label">
              饲料类型
            </text>
            <text class="filter-value">
              {{ selectedFeedTypeName }}
            </text>
          </view>
          <view class="filter-item" @click="showBatchNumberSelector = true">
            <text class="filter-label">
              批次
            </text>
            <text class="filter-value">
              {{ selectedBatchNumberName }}
            </text>
          </view>
          <view class="filter-item">
            <text class="filter-label">
              时间区间
            </text>
            <text class="filter-value">
              本周
            </text>
          </view>
        </view>
      </template>
      <view v-for="(item) in dataList" :key="item.id" class="history-item">
        <view class="item-top">
          <text class="feed-type">
            {{ item.feedType }}
          </text>
          <text :class="getPercentageClass(item.percentage)">
            含水率：{{ item.moistureContent }}%
          </text>
        </view>
        <view class="item-middle">
          <text class="batch-number">
            批次{{ item.batchNumber }}
          </text>
        </view>
        <view class="item-bottom">
          <text class="inspection-time">
            {{ item.detectionTime }}
          </text>
          <text class="inspector">
            检测员：{{ item.detectionPerson }}
          </text>
        </view>
      </view>
    </z-paging>

    <!-- 饲料类型选择器 -->
    <up-action-sheet
      :show="showFeedTypeSelector"
      :actions="feedTypeOptions"
      title="选择饲料类型"
      @close="showFeedTypeSelector = false"
      @select="handleFeedTypeSelect"
    />

    <!-- 批次选择器 -->
    <!-- <up-action-sheet
      :show="showBatchNumberSelector"
      :actions="batchNumberOptions"
      title="选择批次"
      @close="showBatchNumberSelector = false"
      @select="handleBatchNumberSelect"
    /> -->
  </view>
</template>

<script setup lang="ts">
import type { DictPageListRes } from '@/api/common/types';
import type { MoistureData } from '@/api/moisture/types';
import { onMounted, ref } from 'vue';
import { getDictPageList } from '@/api/common';
import { getMoisturePageList } from '@/api/moisture';
import useShare from '@/hooks/use-share';

// 使用分享hook
const { onShareAppMessage, onShareTimeline } = useShare({
  title: '饲料检测历史记录',
  path: '/pages/tab/home/index',
  imageUrl: '/static/images/share.png',
});

// 必须显式调用才能正常分享（小程序平台要求）
onShareAppMessage();
onShareTimeline();

interface HistoryItem {
  id: string;
  feedType: string;
  batchNumber: string;
  inspectionTime: string;
  percentage: number;
  inspector: string;
}

const pagingRef = ref<ZPagingRef<HistoryItem> | null>(null);
const dataList = ref<HistoryItem[]>([]);

// 饲料类型选项
const feedTypeOptions = ref<DictPageListRes[]>([]);

// 当前选中的饲料类型
const selectedFeedType = ref('');
const selectedFeedTypeName = ref('全部');

// 当前选中的批次
const selectedBatchNumber = ref('');
const selectedBatchNumberName = ref('全部');

// 控制批次选择器显示/隐藏
const showBatchNumberSelector = ref(false);

// 控制饲料类型选择器显示/隐藏
const showFeedTypeSelector = ref(false);

// 处理饲料类型选择
function handleFeedTypeSelect(action: any) {
  selectedFeedType.value = action.value;
  selectedFeedTypeName.value = action.name;
  showFeedTypeSelector.value = false;
  // 重新查询数据
  pagingRef.value?.refresh();
}

const getDictList = async () => {
  const res: any = await getDictPageList({
    current: 1,
    pageSize: 100,
    tagId: 398162,
  });
  const feedTypes = res.data.map((item: DictPageListRes) => {
    return {
      name: item.value || '',
      value: item.name || '',
    };
  });
  feedTypeOptions.value = [
    { name: '全部', value: '' },
    ...feedTypes,
  ];
};

function queryList(pageNo: number, pageSize: number) {
  console.log('[ pageNo ] >', pageNo);
  console.log('[ pageSize ] >', pageSize);
  console.log('[ selectedFeedType ] >', selectedFeedType.value);

  // 模拟分页数据
  const start = (pageNo - 1) * pageSize;
  const end = start + pageSize;
  const pageData: MoistureData[] = [];

  // 生成多页模拟数据
  // for (let i = 0; i < 10; i++) {
  //   mockData.forEach((item) => {
  //     pageData.push({
  //       ...item,
  //       id: `${item.id}_${i + 1}`,
  //     });
  //   });
  // }
  getMoisturePageList({
    pageNum: pageNo,
    pageSize,
    feedType: selectedFeedType.value,
    batchNumber: selectedBatchNumber.value,
  }).then((res) => {
    pageData.push(...res.data);
    // 根据选中的饲料类型和批次筛选数据
    let filteredData = pageData;
    if (selectedFeedType.value) {
      filteredData = filteredData.filter(item => item.feedType === selectedFeedType.value);
    }
    if (selectedBatchNumber.value) {
      filteredData = filteredData.filter(item => item.batchNumber === selectedBatchNumber.value);
    }

    const list = filteredData.slice(start, end);
    pagingRef.value?.complete(list);
  });
}

// 根据百分比获取不同颜色的class
function getPercentageClass(percentage: number) {
  if (percentage >= 40) return 'percentage-high';
  if (percentage >= 38) return 'percentage-medium';
  return 'percentage-low';
}

// 页面加载时设置分享菜单
onMounted(() => {
  // #ifdef MP-WEIXIN
  getDictList();
  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });

  // #endif
});
</script>

<style scoped lang="scss">
.history-container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.filter-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.filter-label {
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 8rpx;
}

.filter-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.history-item {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.item-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.feed-type {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.percentage-high {
  font-size: 32rpx;
  font-weight: 600;
  color: #07c160;
}

.percentage-medium {
  font-size: 32rpx;
  font-weight: 600;
  color: #ff9500;
}

.percentage-low {
  font-size: 32rpx;
  font-weight: 600;
  color: #ff3b30;
}

.item-middle {
  margin-bottom: 16rpx;
}

.batch-number {
  font-size: 26rpx;
  color: #666666;
}

.item-bottom {
  display: flex;
  justify-content: space-between;
}

.inspection-time {
  font-size: 26rpx;
  color: #999999;
}

.inspector {
  font-size: 26rpx;
  color: #999999;
}
</style>
